package com.suppor.rpc.proto.serialization;

import com.caucho.hessian.io.Hessian2StreamingInput;
import com.caucho.hessian.io.HessianSerializerInput;
import com.caucho.hessian.io.HessianSerializerOutput;
import com.sun.xml.internal.ws.encoding.soap.SerializationException;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@Component
public class HessianSerialization implements RpcSerializer {
    private static final byte[] EMPTY = new byte[0];

    @Override
    public <T> byte[] serialize(T object) throws IOException {
        if (null == object) {
            return EMPTY;
        }
        byte[] result;
        HessianSerializerOutput output;
        try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            output = new HessianSerializerOutput(os);
            output.writeObject(object);
            output.flush();
            result = os.toByteArray();
        } catch (Exception e) {
            throw new SerializationException(e);
        }
        return result;
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> clazz) throws IOException {
        if (null == data || null == clazz) {
            return null;
        }

        T result;
        try (ByteArrayInputStream in = new ByteArrayInputStream(data)) {
            HessianSerializerInput input = new HessianSerializerInput(in);
            result = (T) input.readObject(clazz);
        }
        return result;
    }
}
